package com.lhbjl;

import com.lhbjl.common.ListNode;

import java.util.List;

/**
 * 两数相加解法
 *
 * @version 0.0.1
 * @author:liuhui
 * @date 2020/5/11
 */
public class AddTwoNumbers {
    /**
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode p = l1, q = l2, curr = head;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (p != null) {
                p = p.next;
            }
            if (q != null) {
                q = q.next;
            }
        }
        /**
         * 如果最后一次循环结束后carry仍然为大于1，则将carry的值写入链表下一个节点作为进位的值
         */
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return head.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(9);

        ListNode l2 = new ListNode(0);
        l2.next = new ListNode(9);
        System.out.println(new AddTwoNumbers().addTwoNumbers(l1, l2));
    }
}
